package com.hhh.springai_test.Advisor;

import org.springframework.ai.document.Document;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Component
public class ZhiPuVectorStore implements VectorStore {

    private final List<Document> documentList = new ArrayList<>();


    @Override
    public void add(List<Document> documents) {
        if(documents != null && !documents.isEmpty()){
            if (documents != null && !documents.isEmpty()) {
                documentList.addAll(documents);
                documentList.forEach(document -> System.out.println("Document added: " + document.getContent()));
                System.out.println("Documents added successfully: " + documents.size());
            } else {
                System.out.println("No documents to add.");
            }
        }
    }

    @Override
    public Optional<Boolean> delete(List<String> idList) {
        if (idList == null || idList.isEmpty()) {
            return Optional.of(false);
        }
        boolean deleted = documentList.removeIf(doc -> idList.contains(doc.getId()));
        return Optional.of(deleted);
    }

    @Override
    public List<Document> similaritySearch(SearchRequest request) {
        System.out.println("Performing similarity search: " + request.getQuery());
        return new ArrayList<>();
    }

    public void readAndAddDocuments(String filePath) {
        try {
            FileSystemResource resource = new FileSystemResource(filePath);
            List<Document> documents = new TikaDocumentReader(resource).read();
            this.add(documents);
        } catch (Exception e) {
            System.err.println("Error reading and adding documents: " + e.getMessage());
        }
    }
}
